package com.example.demo.ui.kotlin

import android.os.Bundle
import android.view.View
import androidx.recyclerview.widget.DividerItemDecoration
import androidx.recyclerview.widget.LinearLayoutManager
import com.example.demo.bese.BaseActivity
import com.example.demo.databinding.ActivityTreeBinding
import com.example.demo.model.BaseBean
import com.example.demo.model.TreeItemBean
import com.example.demo.ui.kotlin.adapter.KTTreeAdapter
import com.example.demo.util.MyJson
import com.example.demo.util.ToastUtil
import com.google.gson.reflect.TypeToken

class KTreeActivity : BaseActivity() {
    private lateinit var binding: ActivityTreeBinding
    private var treeItemList: List<TreeItemBean> = ArrayList()

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        binding = ActivityTreeBinding.inflate(layoutInflater)
        setContentView(binding.root)

        val rqsJson = loadJsonFromAsset("MultiLevelTree.json")
        val baseBean = MyJson.fromJson<BaseBean<*>>(rqsJson, BaseBean::class.java)

        treeItemList = MyJson.toJson(baseBean.getData())?.let {
            MyJson.fromJson<List<TreeItemBean>>(
                it,
                object : TypeToken<ArrayList<TreeItemBean?>?>() {}.type
            )
        }!!

        binding.recyclerView.layoutManager = LinearLayoutManager(this)
        binding.recyclerView.addItemDecoration(
            DividerItemDecoration(
                this,
                DividerItemDecoration.VERTICAL
            )
        )

        val treeAdapter = KTTreeAdapter(this, treeItemList)
        binding.recyclerView.adapter = treeAdapter
        treeAdapter.setOnItemClickListener(object : KTTreeAdapter.OnItemClickListener {
            override fun onItemClick(view: View, position: Int, model: TreeItemBean) {
                ToastUtil.showShort("当前点击的数据为 ${model.typeName}")
            }
        })

    }

    private fun loadJsonFromAsset(fileName: String): String {
        return assets.open(fileName).bufferedReader().use { it.readText() }
    }
}